<template>
  <div class="add">
    <a-modal v-model:visible="visible" title="关联身份权限" @ok="form.onOk" :destroyOnClose="true">
      <a-form-item label="是否开启身份权限认证">
        <a-switch v-model:checked="form.state.check" />
      </a-form-item>
      <div>选择身份</div>
      <div>
        <a-select v-model:value="form.state.value" :options="authOptions" mode="tags" placeholder="请选择身份" style="width: 400px" />
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Form, message, type SelectProps } from 'ant-design-vue'
  import { computed, onUpdated, reactive, ref, watch } from 'vue'

  import { requestSaveCompanyPermissionAuth } from '/@/api/business/company/auth'
  import { requestGetCompanyIdentityList } from '/@/api/business/company/config'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getCompanyInfo } from '/@/storage'

  const { companyId } = getCompanyInfo()

  const props = defineProps({
    visible: { type: Boolean, default: false },
    data: { type: Object, default: null },
  })
  const authOptions = ref<SelectProps['options']>([])
  const initLists = async () => {
    const { responseData } = await requestGetCompanyIdentityList({ companyId })
    authOptions.value = responseData.map((item) => ({
      label: item.identityName,
      value: item.id,
    }))
  }
  initLists()
  onUpdated(() => {
    console.log('props data: ', props.data)
    console.log('key: ', props.data.key)
    form.state.check = props.data.auth === 1
    form.state.value = props.data.identityIds || []
  })
  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })
  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) initData()
    },
  )
  /**
   * 初始化数据
   */
  const initData = () => resetFields()

  /** 表单配置 */
  const form = reactive({
    state: {
      check: false,
      value: [],
    },
    rule: {
      name: [{ required: true, message: '请输入组织名称' }],
    },
    onOk: () => {
      validate()
        .then(async () => {
          // id : companyPermissionAuthId
          const { responseCode } = await requestSaveCompanyPermissionAuth({
            id: props.data.companyPermissionAuthId,
            permissionId: props.data.permissionId,
            auth: form.state.check ? 1 : 0,
            /** 关联身份id列表 */
            identityIds: form.state.value,
          })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('关联身份权限成功')
            visible.value = false
            emits('success')
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, resetFields } = Form.useForm(form.state, form.rule)
</script>

<style lang="less" scoped></style>
